package com.heima.alarm.controller;

import com.heima.redis.lock.RedissonDistributedLock;
import com.heima.redis.template.RedisRepository;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("count")
public class RedisController {

    @Autowired
    RedisRepository redisRepository;

    @Autowired(required = false)
    RedissonDistributedLock lock;

    @Autowired
    Environment env;

    @GetMapping
    public String unCount() {
        // 加锁  永久有效
        RLock rLock = lock.lock("redisson");
        // 2s内有效
//        RLock rLock = lock.lock("redisson",2, TimeUnit.SECONDS);

        try {

            int incr = (int) redisRepository.get("count:11111");

            if (incr > 0) {

                incr = incr - 1;
                redisRepository.set("count:11111", incr);
                System.out.println(env.getProperty("server.port") +"--当前商品库存：" + incr);
            } else {
                System.out.println(env.getProperty("server.port") +"当前商品----库存不足-----" + incr);
            }

        }  finally {
           lock.unlock(rLock);
        }

        return env.getProperty("server.port") + " SUCCESS";
    }

}
